/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package abricots.game.state;

import abricots.MyLog;
import abricots.game.GameEnv;
import abricots.net.common.GameMessage.CommandsMessage;
import abricots.net.common.GameMessage.GameTimeSyncMessage;
import abricots.net.common.GameMessage.WorldDiffMessage;
import abricots.net.common.GameMessage.EntityMessage;
import abricots.net.common.MessageDispatcher;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.minlog.Log;

/**
 *
 * @author charly
 */
public class ConnectingStateMessageDispatcher extends MessageDispatcher {

    private final MyLog log = new MyLog(getClass().getSimpleName(), Log.LEVEL_TRACE);
    private GameEnv env;
    private ConnectingState state;

    public ConnectingStateMessageDispatcher(GameEnv env, ConnectingState state) {
        this.env = env;
        this.state = state;
    }

    @Override
    public void dispatchGameSyncMessage(GameTimeSyncMessage message, Connection connection) {
        long sentTime = message.gameTime;
        if (sentTime == -1) {
            long gameTime = message.newGameTime + connection.getReturnTripTime();
            env.getTimeManager().setGameStartTime(System.currentTimeMillis() - gameTime);
            return;
        }
        long serverSendTime = message.newGameTime;
        long gameTime = env.getTimeManager().getGameTime();
        long diff = serverSendTime - sentTime; // asume we are late > 0
        long newGameTime = gameTime + Math.round(diff * 0.2f);
        log.trace("Time synch msg receivied: server got it at " + serverSendTime + ", sent at " + sentTime + " ; diff=" + diff);
        env.getTimeManager().setGameStartTime(System.currentTimeMillis() - newGameTime);
        if (Math.abs(diff) < 10) {
            state.setSynced(true);
        }
    }

    @Override
    public void dispatchEntitymessage(EntityMessage message, Connection connection) {
    }

    @Override
    public void dispatchWorldDiffMessage(WorldDiffMessage message, Connection connection) {
    }

    @Override
    public void dispatchCommandsMessage(CommandsMessage message, Connection connection) {
    }
}
